package com.xtgg.baby;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.xtgg.R;
import com.xtgg.main.MainActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.ToastUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

public class DeviceSearchActivity extends BaseActivity implements
		OnClickListener {
	JSONArray mArray = new JSONArray();
	Handler mHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			if(msg.what == 1)
			{
				findViewById(R.id.device0 + mArray.size() - 1).setVisibility(View.VISIBLE);
				return;
			}
			
			if(mArray.size() == 0)
			{
				if(!isShow) return;
				
				final Dialog mDialog = new Dialog(DeviceSearchActivity.this, R.style.Dialog_Fullscreen);
				mDialog.setContentView(R.layout.dialog_query);
				mDialog.findViewById(R.id.left).setOnClickListener(
						new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								mDialog.dismiss();
								finish();
							}
						});
				mDialog.findViewById(R.id.right).setOnClickListener(
						new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								mDialog.dismiss();
								startDiscover();
							}
						});
				((TextView)mDialog.findViewById(R.id.content)).setText("未扫描到小兔乖乖设备，是否继续扫描？");
				mDialog.show();
			}
			else
			{
				Intent in = new Intent(DeviceSearchActivity.this,DeviceListActivity.class);
				in.putExtra("array", JSON.toJSONString(mArray));
				startActivity(in);
				finish();
			}
		
		}
	};
	
	boolean isShow = false;
	protected void onResume()
	{
		super.onResume();
		isShow = true;
	}
	
	protected void onPause()
	{
		super.onPause();
		isShow = false;
	}
	
	@SuppressLint("NewApi")
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback()
	{
		private void mLeScan(String paramAnonymousString1, String paramAnonymousString2)
	    {
			JSONObject obj = new JSONObject();
			obj.put("name", paramAnonymousString2);
			obj.put("address", paramAnonymousString1);
			
			if (paramAnonymousString2.contains("SE100") && mArray.size() < 4 && !mArray.contains(obj)
					&& !mRelArray.contains("paramAnonymousString1"))
			{
				mArray.add(obj);
				mHandler.sendEmptyMessage(1);
			} 
	    }

	    public void onLeScan(BluetoothDevice paramAnonymousBluetoothDevice, int paramAnonymousInt, byte[] paramAnonymousArrayOfByte)
	    {
	    	mLeScan(paramAnonymousBluetoothDevice.getAddress(), paramAnonymousBluetoothDevice.getName());
	    }
	};
	
	@SuppressLint("NewApi")
	void startDiscover()
	{
		((DemoApp)getApplicationContext()).mBluetoothAdapter.startLeScan(mLeScanCallback);
		new Timer().schedule(new TimerTask()
		{
			@Override
			public void run() {
				((DemoApp)getApplicationContext()).mBluetoothAdapter.stopLeScan(mLeScanCallback);
				mHandler.sendEmptyMessage(0);
			}
		}, 10000);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_device);
		
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);
		Animation operatingAnim = AnimationUtils.loadAnimation(this, R.anim.rotate);
		findViewById(R.id.search).startAnimation(operatingAnim);
		
		findViewById(R.id.left).setVisibility(View.INVISIBLE);
		
		sendHttpRequest();
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.left:
		case R.id.right:
			showMainView();
			break;
		}
	}
	
	ArrayList<String> mRelArray = new ArrayList<String>();
	private void sendHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("state").equals("1")) {
					JSONArray array = JSON.parseObject(response).getJSONArray("data");
					
					int count = array.size();
					for(int i = 0 ; i< count; i++)
					{
						mRelArray.add(array.getJSONObject(i).getString("andriod_code"));
					}
					
					startDiscover();
				} 
				else if (ruser.getString("state").equals("2"))
				{
					showExitDialog();
				} else {
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "reledDevice");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		MgqRestClient.post(Constants.DEVICEMGT, params, loginHandler);
	}
}
